<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>防抖节流综合练习</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    .box {
      position: relative;
      width: 600px;
      height: 300px;
      margin: 200px auto;
      border: 1px solid #000;
    }
    .box .item {
      position: absolute;
      width: 10px;
      height: 10px;
      background: red;
      top: 50%;
      transform: translateY(-50%);
    }
  </style>
</head>
<body>
  <div class="box">
    <h1>点击计数：0</h1>
    <button id="btn">不优化</button>
    <button id="throttle">节流（throttle）</button>
    <button id="debounce">防抖（debounce）</button>
    <div class="item"></div>
  </div>
  <script>
    let counter = 0
    let i = 0
    function throttle(fn, time) {
      let startTime = 0
      return function () {
        const now = +new Date()
        if (now - startTime > time) {
          fn()
          startTime = now
        }
      }
    }

    function debounce(fn, time) {
      let timer = null
      return function () {
        clearTimeout(timer)
        timer = setTimeout(() => {
          fn()
        }, time)
      }
    }
    const box = document.querySelector('.box')
    const h1 = document.querySelector('.box h1')
    const fn = () => {
      counter++
      for (let i = 0; i < counter; i++) {
        const item = document.createElement('div')
        item.classList.add('item')
        item.style.left = 20 * i + 'px'
        box.appendChild(item)
      }
    }

    document.querySelector('#btn').addEventListener('click', fn)
    document.querySelector('#throttle').addEventListener('click', throttle(fn, 1000))
    document.querySelector('#debounce').addEventListener('click', debounce(fn, 1000))
    
    box.addEventListener('click', function() {
      i++
      h1.innerText = `点击计数：${i}`
    })
  </script>
</body>
</html>